<?php


@session_start();

extract($_REQUEST);
require_once "../lib/config.php";
require_once "../lib/functions.php";
require_once "../lib/pdomanager.php";
require_once "../lib/paginate_class.php";

$pdodbobj=new DB();
$pdodbobj->dbname=DBNAME;
$pdodbobj->hostname=HOST;
$pdodbobj->dbusername=USERNAME;
$pdodbobj->dbpassword=PASSWORD;
$pdodbobj->dbtype=TYPE;
$pdodbobj->portnumber=PORTNUMBER;


$usersarr=array();


if(isset($_POST['oldids']))
{
    if(substr($_POST['oldids'],strlen($_POST['oldids'])-1,1)==",")
    {
        $_POST['oldids']=substr($_POST['oldids'],0,strlen($_POST['oldids']-1));
    }
        
}

$selectfriends=$pdodbobj->fetch_array($pdodbobj->query("Select Active_Friends_IDs from af_users where User_ID = '".$_SESSION['Allyfolio_User_ID']."'"));
if(isset($selectfriends[0]['Active_Friends_IDs']))
{
    $friendsids=$selectfriends[0]['Active_Friends_IDs'];
}
else
{
    $friendsids="''";
}

if(isset($query) && trim($query)!="")
{
    $sqlquery="select User_ID,Full_Name,Allyfolio_User_ID from af_users where (Full_Name like :fullname or Allyfolio_User_ID like :afuserid or Email_ID like :emailid) and Activation_Status='Active' 
    and User_ID in (".$friendsids.") ";
    if(isset($_POST['oldids']) && $_POST['oldids']!="")
    {
        $sqlquery.=" and User_ID not in (".$_POST['oldids'].")";
    }
    $sqlquery.=" order by Allyfolio_User_ID asc limit 100";
    //die;
    $selectfriend=$pdodbobj->fetch_array($pdodbobj->query($sqlquery,array("fullname"=>"%".strtolower($query)."%","afuserid"=>"%".strtolower($query)."%","emailid"=>"%".strtolower($query)."%")));
    
    if($pdodbobj->affectedrows>0)
    {
        
        for($i=0;$i<count($selectfriend);$i++)
        {
            $usersarr[$i]=array("id"=>$selectfriend[$i]['User_ID'],"name"=>$selectfriend[$i]['Full_Name']);
        }
    
    }
    
}
if(count($usersarr)>0)
{
    echo json_encode($usersarr);
}
else
{
    $sqlquery="select User_ID,Full_Name,Allyfolio_User_ID from af_users where Activation_Status='Active' and User_ID in 
    (".$friendsids.")";
    if(isset($_POST['oldids']) && $_POST['oldids']!="")
    {
        $sqlquery.=" and User_ID not in (".$_POST['oldids'].")";
    }
    $sqlquery.=" order by Allyfolio_User_ID asc limit 100";
    //die;
    $selectfriend=$pdodbobj->fetch_array($pdodbobj->query($sqlquery));
    if($pdodbobj->affectedrows>0)
    {
        
        for($i=0;$i<count($selectfriend);$i++)
        {
            $usersarr[$i]=array("id"=>$selectfriend[$i]['User_ID'],"name"=>$selectfriend[$i]['Full_Name']);
        }
    
    }
    echo json_encode($usersarr);
}


?>